
'use strict';
const uniID = require('uni-id-common');
const db = uniCloud.database();

exports.main = async (event, context) => {
	let body = event;
	if (event.body != undefined) {
		body = JSON.parse(event.body)
	}
	
	const { testId, result } = body;
	//验证并解密用户idtoken
	const uniIDIns = uniID.createInstance({ context });

	const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    if (!uid) {
		console.log('checkToken 返回值:',await uniIDIns.checkToken(body.uniIdToken));
        return { code: 403, msg: "身份验证失败" };
    }

	
	
  


  // 数据校验
  if ( !testId || !result) {
    return {
      code: -1,
      message: '缺少必要参数'
    };
  }

  let data = {
    user_id: uid,
    testId: Number(testId),
    created_at: new Date()
  };

  // 处理 testId == "1"
  if (testId == "1") {
    const { factors, totalAverageScore, riskLevel, summary } = result;

    // 校验 result 内的必要字段
    if (!factors || !totalAverageScore || !riskLevel || !summary) {
      return {
        code: -2,
        message: 'result 对象缺少必要字段'
      };
    }

    data.total_score = parseFloat(totalAverageScore);
    data.risk_level = riskLevel;
    data.summary = summary;
    data.factors = factors;
  }
  // 处理 testId == "2"
  else if (testId == "2") {
    const { riskLevel, totalScore } = result;

    // 校验 result 内的必要字段
    if (!totalScore || !riskLevel) {
      return {
        code: -1,
        message: 'result 对象缺少必要字段'
      };
    }

    data.total_score = parseFloat(totalScore);
    data.risk_level = riskLevel;
  }
  // 处理 testId == "3"
  else if (testId == "3") {
    const { shortTermAnxiety,  
    longTermAnxiety,   
    front20Score,      
    back20Score,       
    gender  } = result;
  
    // 校验 result 内的必要字段
    if (!shortTermAnxiety || !longTermAnxiety ||  !front20Score || !back20Score || !gender ) {
      return {
        code: -1,
        message: 'result 对象缺少必要字段'
      };
    }
  
    data.shortTermAnxiety = shortTermAnxiety; 
	data.longTermAnxiety = longTermAnxiety;
	data.front20Score = parseFloat(front20Score);
	data.back20Score = parseFloat(back20Score);
    data.gender = gender;
  }
  // 其他 testId
  else {
    return {
      code: -1,
      message: '无效的 testId'
    };
  }

  // 保存到数据库
  try {
    const resultDb = await db.collection('mind_test_results').add(data);

    return {
      code: 0,
      message: '保存成功',
      data: {
        id: resultDb.id
      }
    };
  } catch (error) {
    return {
      code: -2,
      message: '保存失败',
      error: error.message
    };
  }
};